import { useShopping } from "../../hook//shopping"
import { useEffect, useState } from "react"
import { Table, Space, Popconfirm, message, InputNumber, Statistic, Row, Col, Button, Input } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { useHistory } from "react-router-dom";
import shoppingAPI from "../../api/shopping";
import IndentAPI from "../../api//indent";



//eslint-disable-next-line
export default () => {
  const [{ rows, total }, { getshopping, setCurpage, seteachs }] = useShopping();
  let history = useHistory();
  console.log(rows);
  const { Search } = Input;


  //获取日期
  function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
  }

  const [Rows, setRows] = useState([])

  const [Totals, setTotals] = useState(0)



  useEffect(() => {
    getshopping();
  }, [getshopping]);

  const columns = [
    {
      title: '用户名',
      render: (text, record) => {
        return <a>{record.userid.username}</a>
      }
    },
    {
      title: '商品',
      render: (text, record) => {
        return <a>{record.shoppingid.name}</a>
      }
    },
    {
      title: '单价',
      dataIndex: 'price',
      render: (text, record) => {
        return <a>{record.shoppingid.price}</a>
      }
    },
    {
      title: '数量',
      dataIndex: 'num',
      key: "num",
      render: (text, record) => {
        return <InputNumber min={1} max={record.shoppingid.count} value={record.num} onChange={(value) => onADD(value, record)} />
      }
    },
    {
      title: '总价',
      dataIndex: 'total',
      key: "total"
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Popconfirm title="确认删除？" onConfirm={() => HandleDelete(record._id)} okText="确认"
            cancelText="取消" icon={<QuestionCircleOutlined style={{ color: 'red' }} />}>
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const onChange = (selectedRowKeys, selectedRows) => {
    setRows(selectedRows)

  }

  const dianji = async () => {
    if (Rows.length) {
      let set = []
      for (let index = 0; index < Rows.length; index++) {

        set.push({
          commId: `${Rows[index].shoppingid._id}`,
          quantity: `${Rows[index].num}`
        })

      };
      let data = [];
      data.push({
        userId: Rows[0].userid._id,  // 用户id
        information: set,
        total: Totals, //  总价
        time: getNowFormatDate(), // 购买时间
        state: "待发货"   // 订单状态   
      })
      console.log(data);
      let a = await IndentAPI.postAdd(data[0])
      console.log(a);

    } else {
      message.warning({
        content: "请先勾选",
        duration: 1,
      });
    }


  }


  // 通过用户id找购物车数据
  const onSearch = async () => {
    let data = await shoppingAPI.findshop("61a056228729d31230764bc9")
    console.log(data);
  }



  //删除
  async function HandleDelete(_id) {
    let { status } = await shoppingAPI.del(_id)
    if (status) {
      message.success({
        content: "删除成功！",
        duration: 1,
        onClose: () => {
          getshopping();
        }
      });
    }
  }

  //修改
  async function Handle(_id) {
    history.push(`/info/carts/change/${_id}`)
  }


  async function onADD(value, record) {
    record.num = value;
    record.total = (record.shoppingid.price * record.num).toFixed(2) - 0;
    console.log(record);
    await shoppingAPI.change(record);
    getshopping();
  }


  return <div style={{ marginTop: "20px", marginLeft: "20px" }}>
    <Search
      placeholder="请输入用户id"
      allowClear
      enterButton="搜索"
      size="large"
      onSearch={onSearch}
      style={{ width: "300px" }}
    />
    <Table columns={columns} style={{ marginTop: "20px" }} dataSource={rows} rowKey={record => record._id} pagination={{
      total: total,
      showTotal: total => `总共 ${total} 条`,
      onChange: (page, pageSize) => {
        setCurpage(page)
        seteachs(pageSize)
      },

    }}
      rowSelection={{
        type: "checkbox",
        onChange: onChange,
        onSelect: function (record, selected) {
          if (selected) {
            setTotals(Totals + record.total)
          } else {
            setTotals((Totals - record.total).toFixed(2) - 0)
          }
        }
      }}
    />
    <Row gutter={24}>
      <Col span={24} >
        <Statistic title="总价格" value={Totals} style={{ textAlign: "right", marginRight: "20px" }} />
      </Col>
      <Button type="primary" style={{ marginLeft: "600px" }} onClick={dianji}>生成订单</Button>
    </Row>
  </div>

}


